package com.smartEdu.service.impl.app;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.smartEdu.RongYun.RongYun;
import com.smartEdu.RongYun.RongYun1;
import com.smartEdu.commons.CMap;
import com.smartEdu.commons.LogCvt;
import com.smartEdu.commons.Session;
import com.smartEdu.commons.Tag_Tips;
import com.smartEdu.dao.FindFriendDao;
import com.smartEdu.dao.GroupDao;
import com.smartEdu.dao.RongCloudDao;
import com.smartEdu.exception.JsonException;
import com.smartEdu.exception.ServiceException;
import com.smartEdu.model.CreateRongGroupModel;
import com.smartEdu.model.FindFriendModel;
import com.smartEdu.model.FriendTabModel;
import com.smartEdu.model.GroupIdModel;
import com.smartEdu.model.JoinRongGroupModel;
import com.smartEdu.model.RongCloudModel;
import com.smartEdu.service.RongCloudeService;


@Service(value="rongCloudeServiceImpl")
public class RongCloudeServiceImpl extends BaseServiceImpl implements RongCloudeService{

	@Autowired
	@Qualifier(value="rongCloudDaoImpl")
	public RongCloudDao rongCloudeDao;
	
	@Autowired
	@Qualifier(value="groupDaoImpl")
	public GroupDao groupDao;
	
	@Autowired
	@Qualifier(value="findFriendDaoImpl")
	public FindFriendDao findfriendDao;
	
	@Override
	public void getRongCloudeToken(Session sess) {
		// TODO Auto-generated method stub
		CMap map=null;
		try{
			map=SetToMap(sess);
			int loginTime=(int)(System.currentTimeMillis()/1000);
			String token=com.smartEdu.RongYun.RongYun.GetRongCloudToken(map.gets("id").toString());
			sess.put(Tag_Tips.RESPCODE, "0");
		    sess.put("RNToken",token);
		    
		    RongCloudModel model2=new RongCloudModel();
			model2.setId(map.gets("id").toString());
			model2.setRongToken(token);
			model2.setTimestamp(loginTime);
	        rongCloudeDao.AddOrUpdate(model2);
		}catch (JsonException e){
			LogCvt.error(Tag_Tips.JSONERROR,e);
			throw new ServiceException("rongtoken业务流程出错");
		}
		catch (Exception e) {
			LogCvt.error(e.getMessage(),e);
			throw new ServiceException("rongtoken业务流程出错");
		}
		finally {
			map=null;
		}
		
	}

	@Override
	public void AddGroupId(Session sess) {
		// TODO Auto-generated method stub
		CMap map=null;
		try{
		    map=SetToMap(sess);
		    GroupIdModel models=new GroupIdModel();
		    models.setId(map.gets("id").toString());
		    models.setGroupid(map.gets("groupid").toString());
		    groupDao.addGroupId(models);
		    sess.put(Tag_Tips.RESPCODE, "0");
		}catch (JsonException e){
			LogCvt.error(Tag_Tips.JSONERROR,e);
			throw new ServiceException("groupid json出错");
		}
		catch (Exception e) {
			LogCvt.error(e.getMessage(),e);
			throw new ServiceException("groupid业务流程出错");
		}
		finally {
			map=null;
		}
		
		
	}

	@Override
	public void findFriendById(Session sess) {
		// TODO Auto-generated method stub
		CMap map=null;
		try{
			map=SetToMap(sess);
			
		    List<FindFriendModel> model=new ArrayList<FindFriendModel>();
		    model=null;
		    model=findfriendDao.findFrendByID(map.gets("id"));
		    sess.put(Tag_Tips.RESPCODE, "0");
		    sess.put("result", model);
		}catch (JsonException e){
			LogCvt.error(Tag_Tips.JSONERROR,e);
			throw new ServiceException("findFriendById业务流程出错");
		}
		catch (Exception e) {
			LogCvt.error(e.getMessage(),e);
			throw new ServiceException("findFriendById业务流程出错");
		}
		finally {
			map=null;
		}
		
	}
	@Override
	public void createRongCroup(Session sess) {
		// TODO Auto-generated method stub
		CMap map=null;
		try{
		    map=SetToMap(sess);
		   String name=map.gets("name").toString();
		   CreateRongGroupModel model=new CreateRongGroupModel();
		   RongYun rongYun=new RongYun();
		   String groupid = String.valueOf(System.currentTimeMillis() / 1000);
		   if(rongYun.CreateOrAddGroup(map.gets("id"), groupid, map.gets("name").toString(), "http://api.cn.ronghub.com/group/create.json")){
			   model.setGroupid(groupid);
			   model.setName(map.gets("name").toString());
			   model.setUserid(map.gets("id").toString());
			   rongCloudeDao.CreateRongGroup(model);
			   
			   //先把两个人加入群，达到智能创群的效果
			   RongYun rongYun1=new RongYun();
			   rongYun1.CreateOrAddGroup("140202021028", groupid, map.gets("name").toString(), "http://api.cn.ronghub.com/group/join.json");
			   RongYun rongYun2=new RongYun();
			   rongYun2.CreateOrAddGroup("140202021019", groupid, map.gets("name").toString(), "http://api.cn.ronghub.com/group/join.json");
			   RongYun rongYun3=new RongYun();
			   rongYun3.CreateOrAddGroup("140202021029", groupid,map.gets("name").toString(), "http://api.cn.ronghub.com/group/join.json");
			   RongYun rongYun4=new RongYun();
			   rongYun4.CreateOrAddGroup("130201031035", groupid, map.gets("name").toString(), "http://api.cn.ronghub.com/group/join.json");
			   RongYun rongYun5=new RongYun();
			   rongYun5.CreateOrAddGroup("140202021043", groupid, map.gets("name").toString(), "http://api.cn.ronghub.com/group/join.json");
			   RongYun rongYun6=new RongYun();
			   rongYun6.CreateOrAddGroup("140202021013", groupid, map.gets("name").toString(), "http://api.cn.ronghub.com/group/join.json");
			
			   //把智能推荐的人保存到群组关系表中
			   List<JoinRongGroupModel> list=new ArrayList<JoinRongGroupModel>();
			   JoinRongGroupModel model1=new JoinRongGroupModel();
			   model1.setGroupid(groupid);
			   model1.setUserid("140202021013");
			   list.add(model1);
			   JoinRongGroupModel model2=new JoinRongGroupModel();
			   model2.setGroupid(groupid);
			   model2.setUserid("140202021028");
			   list.add(model2);
			   JoinRongGroupModel model3=new JoinRongGroupModel();
			   model3.setGroupid(groupid);
			   model3.setUserid("140202021029");
			   list.add(model3);
			   JoinRongGroupModel model4=new JoinRongGroupModel();
			   model4.setGroupid(groupid);
			   model4.setUserid("140202021019");
			   list.add(model4);
			   JoinRongGroupModel model5=new JoinRongGroupModel();
			   model5.setGroupid(groupid);
			   model5.setUserid("140202021043");
			   list.add(model5);
			   JoinRongGroupModel model6=new JoinRongGroupModel();
			   model6.setGroupid(groupid);
			   model6.setUserid("130201031035");
			   list.add(model6);
			   //判断创建群者是否在推荐的人中
			   String id=map.gets("id");
			   if(id.equals("140202021013")||id.equals("140202021019")||id.equals("140202021028")
					   ||id.equals("140202021029")||id.equals("140202021043")||id.equals("130201031035")){
				   
			   }else{
				   JoinRongGroupModel model7=new JoinRongGroupModel();
				   model7.setGroupid(groupid);
				   model7.setUserid(id);
				   list.add(model7);
			   }
			  rongCloudeDao.addGroup(list);
			   sess.put(Tag_Tips.RESPCODE, "0");
			   sess.put("groupid",groupid);
			   sess.put("groupName", name);
			   System.out.println(map.gets("name").toString());
		   }else{
			   sess.put(Tag_Tips.RESPCODE, "2");
		   }
		}catch (JsonException e){
			LogCvt.error(Tag_Tips.JSONERROR,e);
			throw new ServiceException("groupid json出错");
		}
		catch (Exception e) {
			LogCvt.error(e.getMessage(),e);
			throw new ServiceException("groupid业务流程出错");
		}
		finally {
			map=null;
		}
		
		
	}

	@Override
	public void joinRongCloudeGroup(Session sess) {
		// TODO Auto-generated method stub
		// TODO Auto-generated method stub
		Boolean flag=false;
		CMap map=null;
		try{
		    map=SetToMap(sess);
		    RongYun rongYun=new RongYun();
		    List<CreateRongGroupModel> model=new ArrayList<CreateRongGroupModel>();
		    model=rongCloudeDao.getGroupById(map.gets("groupid"));
	
			if(model.size()==0){//判断有没有该群组
			   sess.put(Tag_Tips.RESPCODE, "2");
		   }else{ 
			   RongYun1 rongyun1=new RongYun1();
			   String json=rongyun1.QueryGroup(map.gets("groupid").toString());
			   if(rongyun1.isInGroup(map.gets("id").toString(), json)){//判断该人是否已在群组
				   sess.put(Tag_Tips.RESPCODE, "3");
			   }else{//获取在群组信息
			       String groupName=null;
			       for(CreateRongGroupModel createronggroupmodel:model){
				      groupName=createronggroupmodel.getName();
			       }
			       //向融云申请加入群组
			       if(rongYun.CreateOrAddGroup(map.gets("id").toString(),map.gets("groupid").toString(), groupName,"http://api.cn.ronghub.com/group/join.json")){
			          //把该人保存到群组关系表中
			    	 List<JoinRongGroupModel> list=new ArrayList<JoinRongGroupModel>();
					 JoinRongGroupModel model1=new JoinRongGroupModel();
					 model1.setGroupid(map.gets("groupid").toString());
					 model1.setUserid(map.gets("id").toString());
					 list.add(model1);
					rongCloudeDao.addGroup(list);
					 
			    	 sess.put(Tag_Tips.RESPCODE, "0");
			         sess.put("groupname",groupName);
			         sess.put("groupid",map.gets("groupid").toString());
			       }
			   }
		   }
		}catch (JsonException e){
			LogCvt.error(Tag_Tips.JSONERROR,e);
			throw new ServiceException("groupid json出错");
		}
		catch (Exception e) {
			LogCvt.error(e.getMessage(),e);
			throw new ServiceException("groupid业务流程出错");
		}
		finally {
			map=null;
		}
	}

	@Override
	public void getGroupInfo(Session sess) {
		// TODO Auto-generated method stub
		List<CreateRongGroupModel> model=new ArrayList<CreateRongGroupModel>();
		try{
		   model=rongCloudeDao.getGroupInfo();
		   sess.put("groupinfo", model);
		   sess.put(Tag_Tips.RESPCODE, "0");
		}catch (JsonException e){
			LogCvt.error(Tag_Tips.JSONERROR,e);
			throw new ServiceException("groupInfo json出错");
		}
		catch (Exception e) {
			LogCvt.error(e.getMessage(),e);
			throw new ServiceException("groupInfo业务流程出错");
		}
		finally {
			model=null;
		}
	}

	@Override
	public void addfriend(Session sess) {
		// TODO Auto-generated method stub
		CMap map=null;
		try{
			map=SetToMap(sess);
			List<FriendTabModel> model=new ArrayList<FriendTabModel>();
			String sourceUserId=map.gets("fromuserid");
			String targetUserid=map.gets("touserid");
			HashMap<String, String> map1=new HashMap<String,String>();
			if(Double.parseDouble(sourceUserId)>Double.parseDouble(targetUserid)){
				  map1.put("userid1", targetUserid);
				  map1.put("userid2", sourceUserId);
			}else{
				map1.put("userid1", sourceUserId);
				map1.put("userid2", targetUserid);
			   
			}
			 model=rongCloudeDao.queryFriend(map1);
			if(model.size()==0){
				String message1=map.gets("message").toString();
				String message=null;
				if(message1.equals("")){
					message="想加你为好友，你同意吗？";
				}else{
					message="请求加好友:"+message1;
				}
				String str="{\"operation\":\"Request\",\"sourceUserId\":\""+sourceUserId+"\",\"targetUserId\":\""+targetUserid+"\",\"message\":\""+message+"\"}";
				String url="http://api.cn.ronghub.com/message/system/publish.json";
				RongYun1 rongYun=new RongYun1();
				if(rongYun.SendSystemInfo(sourceUserId,targetUserid, "RC:ContactNtf", str, url)){
					 sess.put(Tag_Tips.RESPCODE, "0");
				}
			}else{
				 sess.put(Tag_Tips.RESPCODE, "2");
			}
		
			}catch (JsonException e){
				LogCvt.error(Tag_Tips.JSONERROR,e);
				throw new ServiceException("addfriend json出错");
			}
			catch (Exception e) {
				LogCvt.error(e.getMessage(),e);
				throw new ServiceException("addfriend业务流程出错");
			}
			finally {
			}
	}

	@Override
	public void surefriend(Session sess) {
		// TODO Auto-generated method stub
		CMap map=null;
		try{
			 map=SetToMap(sess);
			String aUserId=map.gets("auserid").toString();
			String bUserid=map.gets("buserid").toString();
			String url="http://api.cn.ronghub.com/message/system/publish.json";
			String url1="http://api.cn.ronghub.com/message/private/publish.json";
			RongYun1 rongYun=new RongYun1();
			FriendTabModel model=new FriendTabModel();
			if(map.gets("type").toString().equals("0")){
				String message="{\"content\":\"我们已是好友，开始聊天吧！\"}";
				if(rongYun.SendSystemInfo(aUserId,bUserid, "RC:TxtMsg", message, url1)
						&&rongYun.SendSystemInfo(bUserid,aUserId, "RC:TxtMsg", message, url1)){
					if(Long.parseLong(aUserId)>Long.parseLong(bUserid)){
						model.setUserid1(bUserid);
						model.setUserid2(aUserId);
					}else{
						model.setUserid1(aUserId);
						model.setUserid2(bUserid);
					}
					rongCloudeDao.AddFrinendTab(model);
					sess.put(Tag_Tips.RESPCODE, "0");
				}
			}else{
				String message="{\"content\":\"拒绝了你的请求\"}";
				rongYun.SendSystemInfo(bUserid,aUserId, "RC:TxtMsg", message, url);
				sess.put(Tag_Tips.RESPCODE, "2");
			}
			
			}catch (JsonException e){
				LogCvt.error(Tag_Tips.JSONERROR,e);
				throw new ServiceException("addfriend json出错");
			}
			catch (Exception e) {
				LogCvt.error(e.getMessage(),e);
				throw new ServiceException("addfriend业务流程出错");
			}
			finally {

			}
	}

	@Override
	public void allMyFriend(Session sess) {
		// TODO Auto-generated method stub
		CMap map=null;
		List<FindFriendModel> model=new ArrayList<FindFriendModel>();
		try{
			
		   map=SetToMap(sess);
		   model=rongCloudeDao.allMyFriend(map.gets("id"));
		   if(model.size()!=0){
		     sess.put("friendinfo", model);
		     sess.put(Tag_Tips.RESPCODE, "0");
		   }else{
			 sess.put(Tag_Tips.RESPCODE, "2");
		   }
		}catch (JsonException e){
			LogCvt.error(Tag_Tips.JSONERROR,e);
			throw new ServiceException("friendinfo json出错");
		}
		catch (Exception e) {
			LogCvt.error(e.getMessage(),e);
			throw new ServiceException("friendinfo业务流程出错");
		}
		finally {
			model=null;
		}
		
	}

	@Override
	public void getGroupInfoById(Session sess) {
		// TODO Auto-generated method stub
		CMap map=null;
		try{
		    map=SetToMap(sess);
		    RongYun rongYun=new RongYun();
		    List<CreateRongGroupModel> model=new ArrayList<CreateRongGroupModel>();
		    model=rongCloudeDao.getGroupByUserId(map.gets("userid"));
		  
		   // sess.put("flag", rongYun.CreateOrAddGroup(map.gets("id").toString(),map.gets("groupid").toString(), model.getName().toString(),"http://api.cn.ronghub.com/group/join.json"));
		   if(model.size()==0){
			   sess.put(Tag_Tips.RESPCODE, "2");
		   }else {
			   sess.put("groupinfo", model);
			   sess.put(Tag_Tips.RESPCODE, "0");
		   }
		}catch (JsonException e){
			LogCvt.error(Tag_Tips.JSONERROR,e);
			throw new ServiceException("groupid json出错");
		}
		catch (Exception e) {
			LogCvt.error(e.getMessage(),e);
			throw new ServiceException("groupid业务流程出错");
		}
		finally {
			map=null;
		}
		
	}

	@Override
	public void deleteFriendById(Session sess) {
		// TODO Auto-generated method stub
		CMap map=null;
		try{
			map=SetToMap(sess);
			String auserid=map.gets("auserid");
			String buserid=map.gets("buserid");
//			HashMap<String, String> map1=new HashMap<String,String>();
//			if(Double.parseDouble(auserid)>Double.parseDouble(buserid)){
//				  map1.put("userid1", buserid);
//				  map1.put("userid2", auserid);
//			}else{
//				map1.put("userid1", buserid);
//			    map1.put("userid2", auserid);
//			}
			FriendTabModel model=new FriendTabModel();
			if(Double.parseDouble(auserid)>Double.parseDouble(buserid)){
				 model.setUserid1(buserid);
				 model.setUserid2(auserid);
			}else{
				 model.setUserid1(auserid);
				 model.setUserid2(buserid);
			}
			  rongCloudeDao.deleteFriendById(model);
			  sess.put(Tag_Tips.RESPCODE, "0");
			
			}catch (JsonException e){
				LogCvt.error(Tag_Tips.JSONERROR,e);
				throw new ServiceException("addfriend json出错");
			}
			catch (Exception e) {
				LogCvt.error(e.getMessage(),e);
				throw new ServiceException("addfriend业务流程出错");
			}
			finally {
			}
		
	}

	
	
}
